package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SaveOrderStrategyContext implements ApplicationContextAware {


    // 在该Map中存储所有的策略对象
    public static final Map<String, SaveOrderStrategy> SAVE_ORDER_STRATEGY_MAP = new HashMap<>();


    // 定义从Map中获取具体策略对象的方法
    public static SaveOrderStrategy getSaveOrderStrategy(String payWay){
        return SAVE_ORDER_STRATEGY_MAP.get(payWay) ;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, SaveOrderStrategy> strategyMap = applicationContext.getBeansOfType(SaveOrderStrategy.class);
        strategyMap.values().forEach(saveOrderStrategy -> {
            String payWay = saveOrderStrategy.getPayWay() ;
            SAVE_ORDER_STRATEGY_MAP.put(payWay , saveOrderStrategy) ;
        });
    }
}